package dao;

import java.util.List;

import javax.persistence.EntityManager;

import org.apache.log4j.Logger;

import bean.TypeCD;
import database.PersistenceUtil;

public class TypeCDDao {
	private static final Logger LOGGER = Logger.getLogger(TypeCDDao.class);

	public static TypeCD findTypeCD(String name) throws Exception {
		EntityManager conn = PersistenceUtil.getEntityManager();
		try {
			List<TypeCD> types = conn.createNamedQuery("TypeCD.findByName", TypeCD.class).setParameter("typeName", name).getResultList();
			if (types.isEmpty()) {
				return null;
			}
			return types.get(0);
		
		} catch (Exception e) {
			LOGGER.error("Error while getting typeCD with name "+ name +" \n" + e.getMessage());
			throw e;
		} finally{
			conn.close();
		}
	}
	
	public static TypeCD findTypeCDById(Long id) throws Exception {
		EntityManager conn = PersistenceUtil.getEntityManager();
		try {
			List<TypeCD> types = conn.createNamedQuery("TypeCD.findByID", TypeCD.class).setParameter("id", id).getResultList();
			if (types.isEmpty()) {
				return null;
			}
			return types.get(0);
		
		} catch (Exception e) {
			LOGGER.error("Error while getting typeCD with id "+ id +" \n" + e.getMessage());
			throw e;
		} finally{
			conn.close();
		}
	}
	
	public static List<TypeCD> getTypeCDs() throws Exception {
		EntityManager conn = PersistenceUtil.getEntityManager();
		try {
			List<TypeCD> types = conn.createNamedQuery("TypeCD.findAll", TypeCD.class).getResultList();
			if (types.isEmpty()) {
				return null;
			}
			return types;
		} catch (Exception e) {
			LOGGER.error("Error while getting types \n" + e.getMessage());
			throw e;
		} finally{
				conn.close();
		}
	}
}
